// GitLab提交日志分析工具 - 主要JavaScript文件

// 全局变量
let currentConfig = null;
let analysisInProgress = false;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    initAnimations();
    // 测试数据库连接
    testConnection();
});

// 初始化应用
function initializeApp() {
    console.log('GitLab提交日志分析工具已加载');
    
    // 设置默认日期
    const today = new Date();
    const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
    
    document.getElementById('startDate').value = formatDate(lastMonth);
    document.getElementById('endDate').value = formatDate(today);
    
    updateDateRange();
}

// 格式化日期
function formatDate(date) {
    return date.toISOString().split('T')[0];
}



// 验证输入
function validateInput(event) {
    const input = event.target;
    const value = input.value.trim();
    
    // 移除之前的验证样式
    input.classList.remove('border-red-500', 'border-green-500');
    
    // 验证逻辑
    if (input.type === 'url') {
        if (value && !isValidUrl(value)) {
            input.classList.add('border-red-500');
            showInputError(input, '请输入有效的URL地址');
        } else if (value) {
            input.classList.add('border-green-500');
        }
    } else if (input.type === 'password') {
        if (value && value.length < 8) {
            input.classList.add('border-red-500');
            showInputError(input, '访问令牌至少需要8个字符');
        } else if (value) {
            input.classList.add('border-green-500');
        }
    } else if (input.required && !value) {
        input.classList.add('border-red-500');
        showInputError(input, '此字段为必填项');
    } else if (value) {
        input.classList.add('border-green-500');
    }
}

// 验证URL格式
function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

// 显示输入错误
function showInputError(input, message) {
    // 移除现有错误提示
    const existingError = input.parentNode.querySelector('.input-error');
    if (existingError) {
        existingError.remove();
    }
    
    // 创建错误提示
    const errorDiv = document.createElement('div');
    errorDiv.className = 'input-error text-red-500 text-xs mt-1';
    errorDiv.textContent = message;
    input.parentNode.appendChild(errorDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (errorDiv.parentNode) {
            errorDiv.remove();
        }
    }, 3000);
}

// 初始化动画
function initAnimations() {
    // 页面加载动画
    anime({
        targets: '.glass-card',
        translateY: [50, 0],
        opacity: [0, 1],
        delay: anime.stagger(200),
        duration: 800,
        easing: 'easeOutExpo'
    });
    
    // 标题文字动画
    if (typeof Splitting !== 'undefined') {
        Splitting();
        
        anime({
            targets: '.hero-title .char',
            translateY: [100, 0],
            opacity: [0, 1],
            delay: anime.stagger(50),
            duration: 1000,
            easing: 'easeOutExpo'
        });
    }
    
    // 统计数字动画
    animateCounters();
}

// 统计数字动画
function animateCounters() {
    const counters = [
        { element: document.getElementById('totalProjects'), target: 12 },
        { element: document.getElementById('totalReports'), target: 156 },
        { element: document.getElementById('totalCommits'), target: 2300 },
        { element: document.getElementById('avgTime'), target: 3.2 }
    ];
    
    counters.forEach(counter => {
        if (counter.element) {
            anime({
                targets: { value: 0 },
                value: counter.target,
                duration: 2000,
                easing: 'easeOutExpo',
                update: function(anim) {
                    const value = Math.round(anim.animatables[0].target.value);
                    if (counter.element.id === 'totalCommits') {
                        counter.element.textContent = (value / 1000).toFixed(1) + 'k';
                    } else if (counter.element.id === 'avgTime') {
                        counter.element.textContent = value.toFixed(1) + 'min';
                    } else {
                        counter.element.textContent = value;
                    }
                }
            });
        }
    });
}

// 快速日期设置
function setQuickDate(period) {
    const today = new Date();
    let startDate = new Date();
    
    switch (period) {
        case 'today':
            startDate = today;
            break;
        case 'week':
            startDate.setDate(today.getDate() - 7);
            break;
        case 'month':
            startDate.setMonth(today.getMonth() - 1);
            break;
        case 'quarter':
            startDate.setMonth(today.getMonth() - 3);
            break;
    }
    
    document.getElementById('startDate').value = formatDate(startDate);
    document.getElementById('endDate').value = formatDate(today);
    
    updateDateRange();
    
    // 添加选中效果
    const buttons = document.querySelectorAll('[onclick^="setQuickDate"]');
    buttons.forEach(btn => {
        btn.classList.remove('bg-blue-500', 'text-white');
        btn.classList.add('bg-blue-50', 'text-blue-700');
    });
    
    event.target.classList.remove('bg-blue-50', 'text-blue-700');
    event.target.classList.add('bg-blue-500', 'text-white');
}

// 更新日期范围显示
function updateDateRange() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    if (startDate && endDate) {
        const start = new Date(startDate);
        const end = new Date(endDate);
        const diffTime = Math.abs(end - start);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        document.getElementById('dateRange').textContent = 
            `${startDate} 至 ${endDate} (${diffDays}天)`;
    } else {
        document.getElementById('dateRange').textContent = '请选择时间范围';
    }
}



async function testConnection() {
    if (!currentConfig) {
        showNotification('请先选择一个项目配置', 'error');
        return;
    }

    const button = event.target;
    const originalText = button.textContent;

    button.textContent = '测试中...';
    button.disabled = true;

    try {
        const response = await fetch(`/api/configs/${currentConfig.id}/test-connection`, {
            method: 'POST'
        });
        const result = await response.json();

        if (result.success) {
            showNotification('连接成功！', 'success');
            button.classList.remove('bg-gray-100', 'hover:bg-gray-200', 'text-gray-700');
            button.classList.add('bg-green-100', 'text-green-700');
        } else {
            showNotification(`连接失败: ${result.message}`, 'error');
            button.classList.remove('bg-gray-100', 'hover:bg-gray-200', 'text-gray-700');
            button.classList.add('bg-red-100', 'text-red-700');
        }
    } catch (error) {
        showNotification('测试连接时发生错误', 'error');
        button.classList.remove('bg-gray-100', 'hover:bg-gray-200', 'text-gray-700');
        button.classList.add('bg-red-100', 'text-red-700');
    }

    setTimeout(() => {
        button.textContent = originalText;
        button.disabled = false;
        button.classList.remove('bg-green-100', 'text-green-700', 'bg-red-100', 'text-red-700');
        button.classList.add('bg-gray-100', 'hover:bg-gray-200', 'text-gray-700');
    }, 2000);
}

// 生成报告
function generateReport() {
    if (analysisInProgress) {
        showNotification('分析正在进行中，请稍候...', 'warning');
        return;
    }
    
    const projectSelect = document.getElementById('projectSelect');
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    if (!projectSelect.value || !startDate || !endDate) {
        showNotification('请完成所有必填项', 'error');
        return;
    }
    
    analysisInProgress = true;
    
    // 显示进度条
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const progressPercent = document.getElementById('progressPercent');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btnText');
    
    progressContainer.classList.remove('hidden');
    generateBtn.disabled = true;
    btnText.textContent = '🔄 分析进行中...';
    
    // 模拟分析过程
    const steps = [
        { text: '正在连接GitLab...', progress: 10 },
        { text: '获取提交日志...', progress: 25 },
        { text: '分析提交数据...', progress: 50 },
        { text: '调用AI模型分析...', progress: 75 },
        { text: '生成报告...', progress: 90 },
        { text: '完成！', progress: 100 }
    ];
    
    let currentStep = 0;
    
    const progressInterval = setInterval(() => {
        if (currentStep < steps.length) {
            const step = steps[currentStep];
            
            anime({
                targets: progressBar,
                width: step.progress + '%',
                duration: 500,
                easing: 'easeOutExpo'
            });
            
            progressText.textContent = step.text;
            progressPercent.textContent = step.progress + '%';
            
            currentStep++;
        } else {
            clearInterval(progressInterval);
            completeAnalysis();
        }
    }, 1500);
}

// 完成分析
function completeAnalysis() {
    setTimeout(() => {
        analysisInProgress = false;
        
        // 隐藏进度条
        const progressContainer = document.getElementById('progressContainer');
        const generateBtn = document.getElementById('generateBtn');
        const btnText = document.getElementById('btnText');
        
        anime({
            targets: progressContainer,
            opacity: [1, 0],
            duration: 500,
            complete: function() {
                progressContainer.classList.add('hidden');
                progressContainer.style.opacity = '1';
            }
        });
        
        generateBtn.disabled = false;
        btnText.textContent = '🚀 生成分析报告';
        
        // 显示成功消息
        showNotification('报告生成成功！正在跳转到报告页面...', 'success');
        
        // 2秒后跳转到报告页面
        setTimeout(() => {
            window.location.href = 'reports.html';
        }, 2000);
    }, 1000);
}

// 打开配置模态框
function openConfigModal() {
    const modal = document.getElementById('configModal');
    modal.classList.remove('hidden');
    
    anime({
        targets: modal,
        opacity: [0, 1],
        duration: 300,
        easing: 'easeOutExpo'
    });
    
    anime({
        targets: '#configModal .bg-white',
        scale: [0.8, 1],
        opacity: [0, 1],
        duration: 300,
        easing: 'easeOutBack'
    });
}

// 关闭配置模态框
function closeConfigModal() {
    const modal = document.getElementById('configModal');
    
    anime({
        targets: '#configModal .bg-white',
        scale: [1, 0.8],
        opacity: [1, 0],
        duration: 200,
        easing: 'easeInBack'
    });
    
    anime({
        targets: modal,
        opacity: [1, 0],
        duration: 200,
        complete: function() {
            modal.classList.add('hidden');
        }
    });
}

// 跳转到配置页面
function goToConfig() {
    window.location.href = 'config.html';
}

// 查看上次报告
function viewLastReport() {
    window.location.href = 'reports.html';
}

// 导出数据
function exportData() {
    if (!currentConfig) {
        showNotification('请先选择项目配置', 'error');
        return;
    }
    
    showNotification('正在准备导出数据...', 'info');
    
    // 模拟导出过程
    setTimeout(() => {
        const data = {
            project: currentConfig.name,
            exportTime: new Date().toISOString(),
            config: currentConfig,
            sampleData: '这是示例导出数据'
        };
        
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `gitlab-export-${Date.now()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showNotification('数据导出成功！', 'success');
    }, 1000);
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-20 right-4 z-50 p-4 rounded-lg shadow-lg max-w-sm transform translate-x-full transition-transform duration-300`;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            notification.classList.add('bg-green-500', 'text-white');
            break;
        case 'error':
            notification.classList.add('bg-red-500', 'text-white');
            break;
        case 'warning':
            notification.classList.add('bg-yellow-500', 'text-white');
            break;
        default:
            notification.classList.add('bg-blue-500', 'text-white');
    }
    
    notification.innerHTML = `
        <div class="flex items-center justify-between">
            <span>${message}</span>
            <button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 300);
    }, 5000);
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函数：节流
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 响应式处理
window.addEventListener('resize', debounce(function() {
    // 处理响应式布局变化
    const width = window.innerWidth;
    
    if (width < 768) {
        // 移动端优化
        document.querySelectorAll('.lg\\:grid-cols-3').forEach(el => {
            el.classList.remove('lg:grid-cols-3');
            el.classList.add('grid-cols-1');
        });
    }
}, 250));

// 错误处理
window.addEventListener('error', function(e) {
    console.error('应用错误:', e.error);
    showNotification('应用出现错误，请刷新页面重试', 'error');
});

// 未处理的Promise拒绝
window.addEventListener('unhandledrejection', function(e) {
    console.error('未处理的Promise拒绝:', e.reason);
    showNotification('网络请求失败，请检查网络连接', 'error');
});

// 导出全局函数供HTML调用
window.setQuickDate = setQuickDate;
window.testConnection = testConnection;
window.generateReport = generateReport;
window.openConfigModal = openConfigModal;
window.closeConfigModal = closeConfigModal;
window.goToConfig = goToConfig;
window.viewLastReport = viewLastReport;
window.exportData = exportData;